package com.skivingcloud.file.controller;

import com.mybatisflex.core.paginate.Page;
import com.skivingcloud.admin.logutils.OperateLog;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.sys.entity.FileInputStreamVo;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import com.skivingcloud.file.entity.SysFile;
import com.skivingcloud.file.service.SysFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.io.Serializable;
import java.util.List;

/**
 * 附件 控制层。
 *
 * @author skivingcloud
 * @since 2024-01-22
 */
@RestController
@Tag(name = "附件接口")
@RequestMapping("/sysFile")
public class SysFileController {

    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Resource
    private SysFileService sysFileService;

    /**
     * 添加附件。
     *
     * @param sysFile 附件
     * @return {@code {code:0,message:"",data:true}} 添加成功，{@code {code:500,message:"",data:false}} 添加失败
     */
    @OperateLog(module="附件", description = "新增附件")
    @PostMapping("/save")
    @Operation(description="保存附件")
    @PreAuthorize("hasAuthority('sysFile:save')")
    public ReturnT<Boolean> save(@Validated @RequestBody @Parameter(description="附件")SysFile sysFile) {
        try{
            sysFile.setId(UuidUtil.get32UUID());
            return ReturnT.ok(sysFileService.save(sysFile));
        }catch(Exception e){
            log.error("新增附件失败", e);
            return ReturnT.error("新增附件失败");
        }
    }

    /**
     * 根据主键删除附件。
     *
     * @param id 主键
     * @return {@code {code:0,message:"",data:true}} 删除成功，{@code {code:500,message:"",data:false}} 删除失败
     */
    @OperateLog(module="附件", description = "删除附件")
    @PostMapping("/remove/{id}")
    @Operation(description="根据主键删除附件")
    public ReturnT<Boolean> remove(@PathVariable("id") @Parameter(description="附件主键")Serializable id) {
        try{
            return ReturnT.ok(sysFileService.removeById(id));
        }catch(Exception e){
            log.error("删除附件失败", e);
            return ReturnT.error("删除附件失败");
        }
    }

    /**
     * 根据主键更新附件。
     *
     * @param sysFile 附件
     * @return {@code {code:0,message:"",data:true}} 更新成功，{@code {code:500,message:"",data:false}} 更新失败
     */
    @OperateLog(module="附件", description = "修改附件")
    @PostMapping("/update")
    @Operation(description="根据主键更新附件")
    @PreAuthorize("hasAuthority('sysFile:update')")
    public ReturnT<Boolean> update(@Validated @RequestBody @Parameter(description="附件主键")SysFile sysFile) {
        try{
            return ReturnT.ok(sysFileService.updateById(sysFile));
        }catch(Exception e){
            log.error("保存附件失败", e);
            return ReturnT.error("保存附件失败！");
        }
    }

    /**
     * 根据附件主键获取详细信息。
     *
     * @param id 附件主键
     * @return 附件详情
     */
    @GetMapping("/getInfo/{id}")
    @Operation(description="根据主键获取附件")
    public ReturnT<SysFile> getInfo(@PathVariable("id") Serializable id) {
        return ReturnT.ok(sysFileService.getById(id));
    }

    /**
     * 分页查询附件。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @PostMapping("/page")
    @Operation(description="分页查询附件")
    @PreAuthorize("hasAuthority('sysFile:page')")
    public ReturnT<Page<SysFile>> page(@RequestBody @Parameter(description="分页信息")PageParameter<SysFile> parameter) {
        Page<SysFile> page = sysFileService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 文件上传，使用formData.append('file', val.raw)来上传文件
     *
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping("/importCommon")
    public ReturnT<List<String>> importCommon(HttpServletRequest request) {
        try {
            SecurityUser user = UserUtil.getCurrentUser();
            StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
            MultipartHttpServletRequest mhr = resolver.resolveMultipart(request);
            List<MultipartFile> files = mhr.getFiles("file");
            String businessId = request.getParameter("businessId");
            String belongModule = request.getParameter("belongModule");//模块
            List<String> fileIds = sysFileService.saveFiles(files, businessId, user, belongModule);
            return ReturnT.ok(fileIds);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return ReturnT.error("上传文件失败");
        }
    }
    
    /**
     * 文件下载
     *
     * @param id       文件记录id
     * @param response 返回
     */
    @RequestMapping("/downloadFile/{id}")
    public void downloadFile(@PathVariable("id") String id, HttpServletResponse response) {
        SysFile fileManagement = sysFileService.getById(id);
        try{
            sysFileService.downloadFile(fileManagement, response);
        }catch(Exception e){
            log.error("下载文件失败", e);
        }
    }
    
    /**
     * 根据业务ID查询附件信息
     * @param businessId 业务ID
     * @return 附件信息
     */
    @GetMapping("/getFileListByBusinessId/{businessId}")
    @Operation(description="根据业务ID查询附件信息")
    public ReturnT<List<SysFile>> getFileListByBusinessId(@PathVariable("businessId") String businessId) {
        return ReturnT.ok(sysFileService.getFileListByBusId(businessId));
    }

    /**
     * 文件上传，使用formData.append('file', val.raw)来上传文件
     *
     * @param fileInputStreamVo 文件流
     * @return 上传结果
     */
    @PostMapping("/importInputStream")
    public ReturnT<String> importInputStream(@RequestBody FileInputStreamVo fileInputStreamVo) {
        try {
            String fileId = sysFileService.saveFileInputStream(fileInputStreamVo.getInputStream(),
                    fileInputStreamVo.getBusinessId(), fileInputStreamVo.getUserId(),
                    fileInputStreamVo.getBelongModule(),
                    fileInputStreamVo.getFileName());
            return ReturnT.ok(fileId);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return ReturnT.error("上传文件失败");
        }
    }
}
